/* In order to work correctly in Internet Explorer, this script issues a call to
 * document.write when it is loaded. Therefore, the defining SCRIPT element
 * MUST NOT contain the 'defer' attribute nor otherwise be loaded in a
 * deferred manner. (The DOM must still be incomplete when this script executes.) */

/**
 * Registers an event callback to be fired off whenever the DOM is completely
 * available.
 */
var ondomload = (function() {

  var callbacks = null;
  var domisloaded = false;
  
  // The below commented out code will actually be executed in Internet Explorer.
  // Conditional comments are very controversial
  // but in my opinion are more reliable than other browser "sniffing" methods.
  // And since this hack is specifically for IE...
/*@cc_on @if (@_jscript)

  // A deferred, external script is executed after the DOM is available in IE.
  // I know of no formal specification for this behavior.
  // However, it appears consistent across IE 6 through 8.
  // MUST use a document.write to emit the SCRIPT (if being placed dynamically)
  //   or readyState never reaches 'complete'.
  //   (I don't know why, but that's just the way it is.)
  // http://dean.edwards.name/weblog/2005/09/busted/
  document.write('<SCRIPT src="//:" defer></SCRIPT>');
  var script = document.documentElement.lastChild.lastChild;
  script.onreadystatechange = function() {
    if (this.readyState == 'complete') {
      this.onreadystatechange = null;
      this.parentNode.removeChild(this);
      firedomload();
    }
  };
  
  @else @*/

  var fn;
    
  // Try to listen for DOMContentLoaded
  // Default to 'onload'
  if (document.addEventListener) {
    fn = function() {
      document.removeEventListener('DOMContentLoaded', fn, false);
      document.removeEventListener('load', fn, false);
      firedomload();
    }
    document.addEventListener('DOMContentLoaded', fn, false);
    document.addEventListener('load', fn, false);
  } else {
    fn = window.onload;
    window.onload = function() {
      window.onload = fn;  // be a good citizen
      if (typeof fn == 'function') setTimeout(fn, 0);
      firedomload();
    };
  }
    
/*@end @*/

  /**
   * Fire off all callbacks only once, and then release them.
   */
  function firedomload() {
    if (domisloaded) return;
    domisloaded = true;
    for (var i=0; i<callbacks.length; i++)
      setTimeout(callbacks[i], 0);
    callbacks = null;
  }

  /**
   * Register a callback
   * or call it if the document is available immediately.
   */
  return function(callback) {
    if (domisloaded) return callback();
    if (!callbacks) callbacks = [];
    callbacks.push(callback);
  };
})();
